/*
 * @Description: 目录上传Excel
 * @Author: Zzt
 * @Date: 2022-10-18 14:46:21
 * @LastEditTime: 2022-10-24 18:34:18
 */

import { useEffect, useState } from 'react';
import { Button, Modal, Steps, Typography, Upload } from 'antd';
import cs from 'classnames';
import classNames from 'classnames/bind';
import { uploadPath } from '@/api/upload';
import { saveItemFiles } from '@/api/standardizedDetection/detectionTask';
import { delItemById } from '@/utils/list';
import { UploadOutlined } from '@ant-design/icons';
import { useStandardizedDetectionContext } from '../../contexts/StandardizedDetectionContext';
import type { UploadChangeParam, UploadFile } from 'antd/lib/upload';
import styles from '../../styles/uploadFolderDialog.module.scss';

const cx = classNames.bind(styles);

const { Step } = Steps;

const UploadFolder = (props: any) => {
  const { onClose, visible } = props;
  const { activeStandardized, updateStandardizedList, selectAT, selectFond } =
    useStandardizedDetectionContext();

  const [levelList, setLevelList] = useState([]);
  // 当前step
  const [current, setCurrent] = useState(0);
  // 当前层级是否已上传标志
  const [currentUploaded, setCurrentUploaded] = useState(false);
  // 存储上传成功后返回的完整条目数据
  const [latestRecord, setLatestRecord] = useState({});
  // 已经上传的层级
  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    if (visible) {
      // 获取档案类型下层级
      setLevelList(delItemById(0, selectAT.levelList, 'level'));
    }
  }, [visible]);

  useEffect(() => {
    if (visible && activeStandardized && JSON.stringify(activeStandardized) !== '{}') {
      setFileList(activeStandardized.attItemsList);
    }
  }, [activeStandardized]);

  useEffect(() => {
    if (
      visible &&
      activeStandardized &&
      JSON.stringify(activeStandardized) !== '{}' &&
      levelList.length > 0
    ) {
      setUploadedFlag();
    }
  }, [fileList, levelList]);

  useEffect(() => {
    setUploadedFlag();
  }, [current]);

  const setUploadedFlag = () => {
    setCurrentUploaded(
      fileList.find((item) => item.level === levelList[current].level)?.status || false
    );
  };

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    if (JSON.stringify(latestRecord) === '{}') {
      onClose();
    } else {
      onClose(latestRecord);
    }
    setCurrent(0);
    setLevelList([]);
    setFileList([]);
    setCurrentUploaded(false);
    setLatestRecord({});
  };

  /**
   * @description 步骤条，前进一步
   */
  const next = () => {
    setCurrent(current + 1);
  };

  /**
   * @description 步骤条，返回一步
   */
  const prev = () => {
    setCurrent(current - 1);
  };

  /**
   * @description: 上传变化回调
   * @param {any} info
   */
  const onChange = (info: UploadChangeParam<UploadFile>) => {
    const { file } = info;
    if (file.status === 'done') {
      saveExcel(file, file.response);
    }
  };

  const saveExcel = (file: UploadFile, res: any) => {
    const params: any = { id: activeStandardized.id };
    params.itemAtt = {
      fileSize: file.size,
      fileUrl: res.data?.url || '',
      level: levelList[current].level,
      status: true
    };

    saveItemFiles(params).then((res) => {
      updateStandardizedList(res.data);
    });
  };
  return (
    <Modal
      visible={visible}
      title="目录上传Excel"
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          关闭
        </Button>,
        <>
          {current > 0 && (
            <Button key="prve" onClick={() => prev()}>
              上一步
            </Button>
          )}
        </>,
        <>
          {current < levelList.length - 1 && (
            <Button
              key="next"
              type="primary"
              onClick={() => {
                next();
              }}
            >
              下一步
            </Button>
          )}
        </>,
        <>
          {current === levelList.length - 1 && (
            <Button key="finish" type="primary" onClick={() => onCancel()}>
              完成
            </Button>
          )}
        </>
      ]}
    >
      <p>
        全宗:{selectFond.fondName} - 档案类型{''}:{selectAT.atName}
      </p>
      <Typography.Paragraph strong>按层级上传EXCEL</Typography.Paragraph>
      <div className={cx('steps-wrap')}>
        <Steps current={current}>
          {levelList.map((item) => (
            <Step key={item.level} title={item.levelName} />
          ))}
        </Steps>
        <div className="steps-content">
          <Typography.Text className={cx('step--title')}>
            请上传{levelList[current]?.levelName}条目
          </Typography.Text>
          {currentUploaded && <Typography.Text type="success">已上传</Typography.Text>}
          {levelList.map((item) => (
            <Upload
              key={item.level}
              accept=".xlsx,.csv,.xls"
              action={uploadPath}
              name="file"
              maxCount={1}
              className={cs(
                cx('upload-wrap'),
                levelList[current].levelName === item.levelName ? cx('upload--current') : null
              )}
              onChange={onChange}
            >
              <Button icon={<UploadOutlined />}>点击上传</Button>
            </Upload>
          ))}
        </div>
      </div>
    </Modal>
  );
};
export default UploadFolder;
